<template>
  <el-dialog v-model="props.visible" :title="title" @close="handleClose" width="90%" top="3vh">
    <div style="padding: 10px 20px">
      <el-row :gutter="16" style="margin-bottom: 20px">
        <el-col :span="8">
          <div>工序订单：{{ titleDetail.no || '--' }}</div>
        </el-col>
        <el-col :span="8">
          <div>产品名称：{{ titleDetail.productName || '--' }}</div>
        </el-col>
        <el-col :span="4">
          <div>总数：{{ titleDetail.orderCount || '--' }}</div>
        </el-col>
        <el-col :span="4">
          <div>工单数量总数：{{ totalNeedNumber }}</div>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <div>开始时间：{{ titleDetail.planBeginTime || '--' }}</div>
        </el-col>
        <el-col :span="8">
          <div>结束时间：{{ titleDetail.planEndTime || '--' }}</div>
        </el-col>
        <el-col :span="4">
          <div>待派发：{{ titleDetail.unfinishedCount || 0 }}</div>
        </el-col>
        <el-col :span="4">
          <div>已派发：{{ titleDetail.distributeCount || 0 }}</div>
        </el-col>
      </el-row>
    </div>
    <div class="twoTableView">
      <div style="display: flexl;flex-direction: column;width: 39%;">
        <div class="selectBoxes">
          <el-select v-model="selectedWorkshop" placeholder="请选择车间" filterable @change="handleWorkshopChange">
            <el-option v-for="workshop in workshopOptions" :key="workshop.id" :label="workshop.orgName"
                       :value="workshop.id"></el-option>
          </el-select>
          <el-select v-model="selectedLine" placeholder="请选择产线" filterable :disabled="!selectedWorkshop"
                     style="margin:0 10px;" @change="srarchEquipmentName()">
            <el-option v-for="line in lineOptions" :key="line.id" :label="line.name" :value="line.id">
              <span style="float: left">{{ line.name }}</span>
              <span
                  style="
									float: right;
									color: var(--el-text-color-secondary);
									font-size: 13px;
								"
              >
        {{ line.orgAbbreviation }}
      </span>
            </el-option>
          </el-select>
          <!--					<el-button icon="Search" :disabled="!selectedLine" @click="srarchEquipmentName()">搜索</el-button>-->
        </div>
        <el-table ref="table" :data="equipmentData" style="width: 100%" height="500px" row-key="id" border
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column type="index" label="序号" width="55" align="center"/>
          <el-table-column label="设备名称" prop="equipmentName" show-overflow-tooltip align="center" sortable/>
          <el-table-column label="设备编码" prop="equipmentCode" show-overflow-tooltip align="center" sortable/>
        </el-table>
      </div>
      <el-table ref="table" :data="multipleSelection" style="width: 59%" height="542px" row-key="id" border>
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column label="设备名称" prop="equipmentName" min-width="80" show-overflow-tooltip align="center"
                         sortable/>
        <el-table-column label="工装名称" prop="toolId" min-width="80" show-overflow-tooltip align="center">
          <template #default="scope">
            <el-select v-model="scope.row.toolId" placeholder="请选择" @change="e => toolChange(e,scope)" clearable>
              <el-option v-for="(item, index) in toolData" :key="item.id" :value="item.id" :label="item.code">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column label="工装台账" prop="toolRegisterId" min-width="80" show-overflow-tooltip align="center">
          <template #default="scope">
            <el-select v-model="scope.row.toolRegisterId" placeholder="请选择" @change="e => needFind(e, scope.row, 'toolRegisterId')">
              <el-option v-for="(item, index) in scope.row.toolRegister" :key="item.toolRegisterId" :value="item.toolRegisterId" :label="item.toolRegisterName">
              </el-option>
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column label="工单数量" prop="needNumber" min-width="80" show-overflow-tooltip align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.needNumber"
                             @change="e => needFind(e, scope.row, 'needNumber')"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="每日派工数量" prop="daySendWorkNumber" min-width="80" show-overflow-tooltip align="center">
          <template #default="scope">
            <div style="display: flex">
              <el-input-number style="width: 200px" v-model="scope.row.daySendWorkNumber"></el-input-number>
              <el-button style="margin-left:5px" v-if="scope.$index === 0"  type="text"
                         @click="copyDaySendWorkNumber">复制
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import {ref, watch} from 'vue';
import {
  queryToolingByWork,
  queryEquipment
} from '@/api/scheduling/dispatchManagement';
import {lineAll} from '@/api/baseData/productionLine';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Document, Edit} from '@element-plus/icons-vue';

const props = defineProps({
  visible: Boolean,
  form: Object,
  title: String,
  handleAddSubmit: Function,
  materialList: Array,
  putMaterialData: Array,
  equipmentData: Array,
  titleDetail: Array,
  handleClose: Function
});

const emit = defineEmits(['update:visible', 'update:putMaterialData']);

const toolData = ref([]);
const equipmentData = ref([]);
const workshopOptions = ref([]);
const lineOptions = ref([]);
const selectedWorkshop = ref(null);
const selectedLine = ref(null);

watch(() => props.visible, (newValue, oldValue) => {
  if (newValue) {
    selectedLine.value = null;
    multipleSelection.value = [];
    equipmentData.value = [];
    queryToolingByWork({id: props.titleDetail.id}).then(res => {
      if (res.code === 200) {
        toolData.value = res.data;
      }
    });

    lineAll({current: 1, pageSize: 100000}).then(res => {
      if (res.code === 200) {

        const list = buildTree(res.data.records.map((item) => {
          return {
            ...item.extension,
            ...item
          };
        }));
        workshopOptions.value = list[0].children;
      }
    });
  }
});
// 添加计算属性，用于计算工单数量总和
const totalNeedNumber = computed(() => {
  return multipleSelection.value.reduce((total, item) => {
    return total + (item.needNumber || 0);
  }, 0);
});
const toolChange = (e, scope) => {
  needFind(e, scope.row, 'toolRegisterId')
  // const  changeToolRegister=multipleSelection.value.map(item=>{

  // 	if(item.id===scope.row.id){
  // 		const toolRegisterList= toolData.value.find(i=>i.id===e)?.children
  // 		return{...item,
  // 			toolRegister:toolRegisterList
  // 		}
  // 	}
  // 	return item
  // })
  // multipleSelection.value=changeToolRegister

}
const toolRegister = () => {

}

const copyDaySendWorkNumber = () => {
  const list = JSON.parse(JSON.stringify(multipleSelection.value));
  const daySendWorkNumber = list[0].daySendWorkNumber
  for (const item of list) {
    item.daySendWorkNumber = daySendWorkNumber
  }
  multipleSelection.value = list
}

// 搜索设备
const srarchEquipmentName = () => {
  queryEquipment({
    procedureId: props.titleDetail.procedureId,
    organizationId: selectedLine.value
  }).then(res => {
    if (res.code === 200) {
      equipmentData.value = res.data;
    }
  });
  // axiosInstance.post('/api/basedataEquipment/getPage', {
  //   procedureId: props.titleDetail.procedureId,
  //   organizationId: ,
  //   current: 1,
  //   pageSize: 100000
  // }).then(res => {
  //   if (res.code === 200) {
  //     equipmentData.value = res.data;
  //   }
  // });
};

const handleWorkshopChange = (workshopId) => {
  const selectedWorkshopData = workshopOptions.value.find(workshop => workshop.id === workshopId);
  lineOptions.value = selectedWorkshopData ? selectedWorkshopData.children : [];
  selectedLine.value = null; // Reset selected line when workshop changes
};

const buildTree = (items) => {
  const itemMap = {};
  const rootItems = [];
  items.forEach((item) => {
    itemMap[item.id] = {...item, name: item.orgName, children: []};
  });
  items.forEach((item) => {
    if (!item.parentId || item.parentId === '0') {
      rootItems.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });

  return rootItems;
};

const needFind = (e, row, type) => {
  const needData = multipleSelection.value.map(item => {
    if (item.index_id === row.index_id) {
      return {...item, [type]: e};
    }
    return item;
  });
  props.putMaterialData = needData;


};

const closeModal = () => {
  emit('update:visible', false);
};

const multipleSelection = ref([]);
const handleSelectionChange = (e) => {
  const list = JSON.parse(JSON.stringify(e));
  for (const item of list) {
    item.equipmentId = item.id;
    item.toolId = toolData.value[0].id;
    item.toolRegister = toolData.value[0].children;
  }
  const num = props.titleDetail.unfinishedCount;
  const daySendWorkNumber = Math.ceil(num / list.length);
  for (const item of list) {
    item.equipmentId = item.id;
    item.toolId = toolData.value[0].id;
    item.needNumber = daySendWorkNumber;
    item.toolRegister = toolData.value[0].children;
  }
  multipleSelection.value = list;
};

const handleSubmit = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择数据！');
    return;
  }
  const allFieldsFilled = multipleSelection.value.every(item =>
      item.equipmentId && item.toolId && item.needNumber && item.daySendWorkNumber
  );
  if (!allFieldsFilled) {
    // 显示错误提示
    ElMessage.error('请确保设备名称、工装名称、工单数量、每日派工数量均已填写！');
    return;
  }
  emit('update:putMaterialData', multipleSelection.value);
  props.handleAddSubmit();
};
</script>
<style scoped>
.twoTableView {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.selectBoxes {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>